<template>
  <view class="h-100vh flex flex-col overflow-hidden bg-[#f8f8f8]">
    <S1Header title="库存管理" :on-back="onBack" />
    <!-- 搜索框 -->
    <view class="h-80rpx flex items-center gap-10% bg-white px-20rpx">
      <input
        v-model="keyword"
        class="flex-1 border border-[rgb(229,229,229,100%)] rounded-[20px] bg-[rgb(245,247,250,100%)] px-10rpx py-10rpx pl-60rpx text-25rpx text-[#333] font-sans shadow-[0_1px_1px_rgb(0,0,0,25%)]"
        placeholder="搜索货主或批次"
        confirm-type="search"
        @confirm="onSearch"
      >
      <image
        src="https://ceshiweb.picaime.com/static/images/search.png"
        class="absolute left-28rpx h-30rpx w-30rpx object-cover p-10rpx"
      />
      <view
        class="h-40rpx w-100rpx flex text-32rpx font-500"
        @click="toggleFilter"
      >
        <image
          class="h-40rpx w-32rpx"
          src="https://ceshiweb.picaime.com/static/images/filter.png"
        />
        <span class="ml-4rpx text-[#333] leading-40rpx">筛选</span>
      </view>
    </view>
    <!-- 下面的按钮 -->
    <view
      class="mt-20rpx flex justify-between border-b border-b-[#f5f5f5] bg-white p-6rpx"
    >
      <view
        class="flex-1 rounded-5rpx p-20rpx text-center text-32rpx transition-all duration-300 ease-in-out"
        :class="{
          'font-bold text-[#43cf7c] border-b-4 border-[#43cf7c]':
            activeTab === 0,
          'text-[#808080]': activeTab !== 0,
        }"
        @click="changeTab(0)"
      >
        批次库存
      </view>
      <view
        class="flex-1 rounded-5rpx p-20rpx text-center text-32rpx transition-all duration-300 ease-in-out"
        :class="{
          'font-bold text-[#43cf7c] border-b-4 border-[#43cf7c]':
            activeTab === 1,
          'text-[#808080]': activeTab !== 1,
        }"
        @click="changeTab(1)"
      >
        分类库存
      </view>
    </view>

    <!-- 下面的信息 -->
    <scroll-view
      scroll-y
      class="max-h-[calc(100vh-350rpx)] flex-1 px-15rpx"
      refresher-enabled
      :refresher-triggered="refresherTriggered"
      @refresherrefresh="onRefresh"
    >
      <view class="main-container">
        <!-- 批次库存列表 -->
        <template v-if="activeTab === 0">
          <view
            v-for="i in filteredProducts"
            :key="i.id"
            class="relative mt-20rpx h-164rpx w-full flex flex-col justify-center border border-[#efefef] bg-white shadow-[0_0_5rpx_0_rgb(221,221,221,60%)]"
            @click="onPiciClick(i)"
          >
            <view class="mb-10rpx ml-30rpx flex items-center">
              <view class="text-36rpx text-[rgb(0,0,0,100%)] font-400">
                {{ i.huozhu_name }}
              </view>
              <view
                class="ml-20rpx h-41rpx w-107rpx rounded-7rpx bg-[#43cf7c] text-center text-white leading-41rpx"
              >
                {{ i.pici }}
              </view>
            </view>
            <!-- 下面的时间 -->
            <view class="ml-30rpx text-30rpx text-[rgb(166,166,166,100%)]">
              {{ i.time }}
            </view>
            <!-- 右侧状态和箭头 -->
            <view
              class="absolute right-30rpx top-0 h-full flex flex-col items-end justify-center"
            >
              <!-- 状态标签 -->
              <view
                class="mb-10rpx rounded-[10rpx] px-16rpx py-6rpx text-30rpx"
                :style="getStatusStyle(getStatusText(i.status))"
              >
                {{ getStatusText(i.status) }}
              </view>
              <!-- 箭头 -->
              <view
                class="h-50rpx w-60rpx flex items-center justify-center border border-[#ddd] rounded-[6rpx]"
              >
                <image
                  src="https://ceshiweb.picaime.com/static/images/report/right.png"
                  class="h-30rpx w-30rpx"
                />
              </view>
            </view>
          </view>
        </template>

        <!-- 分类库存列表 -->
        <template v-if="activeTab === 1">
          <view
            v-for="category in filteredCategories"
            :key="category.id"
            class="relative mt-20rpx h-164rpx w-full flex flex-col justify-center border border-[#efefef] bg-white shadow-[0_0_5rpx_0_rgb(221,221,221,60%)]"
            @click="onCategoryClick(category)"
          >
            <view class="mb-10rpx ml-30rpx flex items-center">
              <view class="text-36rpx text-[rgb(0,0,0,100%)] font-400">
                {{ category.name }}
              </view>
              <view
                v-if="category.child && category.child.length > 0"
                class="ml-20rpx h-41rpx w-107rpx rounded-7rpx bg-[#43cf7c] text-center text-white leading-41rpx"
              >
                {{ category.id }}
              </view>
            </view>
            <!-- 子分类 -->
            <view class="ml-30rpx flex flex-wrap">
              <template v-if="category.child && category.child.length > 0">
                <view
                  v-for="subItem in category.child.slice(0, 2)"
                  :key="subItem.id"
                  class="mb-10rpx mr-16rpx border border-[#ddd] rounded-30rpx bg-[#eceef2] px-20rpx py-8rpx text-28rpx text-[#333]"
                  @click.stop="onSubCategoryClick(category, subItem)"
                >
                  {{ subItem.name }}
                </view>
                <view
                  v-if="category.child.length > 2"
                  class="mb-10rpx mr-16rpx border border-[#ddd] rounded-30rpx bg-[#eceef2] px-20rpx py-8rpx text-28rpx text-[#333]"
                >
                  等{{ category.child.length }}个
                </view>
              </template>
              <view
                v-if="!category.child || category.child.length === 0"
                class="mb-10rpx mr-16rpx border border-[#ddd] rounded-30rpx bg-[#eceef2] px-20rpx py-8rpx text-28rpx text-[#333]"
              >
                无子分类
              </view>
            </view>
            <!-- 右侧状态和箭头 -->
            <view
              class="absolute right-30rpx top-0 h-full flex flex-col items-end justify-center"
            >
              <!-- 状态标签 -->
              <view
                class="mb-10rpx rounded-[10rpx] px-16rpx py-6rpx text-30rpx"
                style="backgroundcolor: rgba(209, 255, 227, 1); color: #43cf7c"
              >
                分类
              </view>
              <!-- 箭头 -->
              <view
                class="h-50rpx w-60rpx flex items-center justify-center border border-[#ddd] rounded-[6rpx]"
              >
                <image
                  src="https://ceshiweb.picaime.com/static/images/report/right.png"
                  class="h-30rpx w-30rpx"
                />
              </view>
            </view>
          </view>
        </template>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { computed, ref } from 'vue';
import { getDayReport } from '@/api/category';
import { getAllPiciData } from '@/api/order';
import S1Header from '@/components/S1Header.vue';

const products = ref([]);
const categories = ref([]);
const loading = ref(false);
const refresherTriggered = ref(false);

// 获取批次数据
const fetchProducts = async (status) => {
  try {
    loading.value = true;
    const res = await getAllPiciData({
      status,
    });
    if (res.code === 200) {
      products.value = res.data;
    }
  }
  catch (error) {
    console.error('获取批次数据失败:', error);
  }
  finally {
    loading.value = false;
    refresherTriggered.value = false;
  }
};

// 获取分类数据
const fetchCategories = async () => {
  try {
    loading.value = true;
    const res = await getDayReport({
      page: 1,
      ishuozhuorfenlei: 1,
      limit: 10000,
    });
    if (res.code === 200) {
      categories.value = res.data.data;
    }
  }
  catch (error) {
    console.error('获取分类数据失败:', error);
  }
  finally {
    loading.value = false;
    refresherTriggered.value = false;
  }
};

onLoad(() => {
  fetchProducts(0);
});

function onBack() {
  uni.navigateBack();
}
const keyword = ref('');

function onSearch() {
  if (activeTab.value === 0) {
    fetchProducts(activeTab.value);
  }
  else {
    // 分类搜索直接使用本地过滤
    // 这里不需要重新请求API
  }
}

// 下拉刷新
const onRefresh = () => {
  refresherTriggered.value = true;
  if (activeTab.value === 0) {
    fetchProducts(activeTab.value);
  }
  else {
    fetchCategories();
  }
};

function toggleFilter() {
  console.log('切换筛选');
}
// 按钮
const activeTab = ref(0);

function changeTab(tabIndex) {
  activeTab.value = tabIndex;
  if (tabIndex === 0) {
    fetchProducts(tabIndex);
  }
  else {
    fetchCategories();
  }
}

// 批次库存过滤
const filteredProducts = computed(() => {
  if (keyword.value && activeTab.value === 0) {
    return products.value.filter(
      item =>
        item.huozhu_name.includes(keyword.value)
        || String(item.pici).includes(keyword.value),
    );
  }
  return products.value;
});

// 分类库存过滤
const filteredCategories = computed(() => {
  if (keyword.value && activeTab.value === 1) {
    return categories.value.filter(item => item.name.includes(keyword.value));
  }
  return categories.value;
});

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '在售';
    case 2:
      return '售完';
    case 3:
      return '结完';
    default:
      return '未知';
  }
};

// 颜色
const getStatusStyle = (status) => {
  if (status === '在售') {
    return {
      backgroundColor: 'rgba(209, 255, 227, 1)',
      color: '#43cf7c',
    };
  }
  else if (status === '售完') {
    return {
      backgroundColor: 'rgba(250, 207, 165, 1)',
      color: '#ff9744',
    };
  }
  else if (status === '结完') {
    return {
      backgroundColor: 'rgba(228, 218, 250, 1.0)',
      color: '#a755ff',
    };
  }
  else {
    return {
      backgroundColor: 'rgba(180, 225, 255, 1.0)',
      color: '#3d9af9',
    };
  }
};

// 点击分类库存项
const onCategoryClick = (category) => {
  console.log('点击分类库存:', category.id);

  // 将分类数据和API参数存入缓存
  const cacheData = {
    sourceData: category, // 原始分类数据
    apiParams: {
      cat_id: category.id,
      cat_id_2: '',
      pici_id: '',
      index: 0,
      page: 1,
      limit: 10,
      saleStatus: 1,
      goods_name: '',
    },
    pageType: 'category',
  };

  uni.setStorageSync('stockPageData', JSON.stringify(cacheData));

  // 直接跳转，不传URL参数
  uni.navigateTo({
    url: '/pages/tab/batchadd/batchadd',
    success: () => {
      console.log('跳转成功，数据已缓存');
    },
    fail: (err) => {
      console.error('跳转失败:', err);
    },
  });
};

// 点击子分类
const onSubCategoryClick = (parentCategory, subCategory) => {
  console.log('点击子分类:', parentCategory.id, subCategory.id);

  // 将子分类数据和API参数存入缓存
  const cacheData = {
    sourceData: {
      parentCategory,
      subCategory,
    },
    apiParams: {
      cat_id: parentCategory.id,
      cat_id_2: subCategory.id,
      pici_id: '',
      index: 0,
      page: 1,
      limit: 10,
      saleStatus: 1,
      goods_name: '',
    },
    pageType: 'subcategory',
  };

  uni.setStorageSync('stockPageData', JSON.stringify(cacheData));

  // 直接跳转，不传URL参数
  uni.navigateTo({
    url: '/pages/tab/batchadd/batchadd',
    success: () => {
      console.log('跳转成功，数据已缓存');
    },
    fail: (err) => {
      console.error('跳转失败:', err);
    },
  });
};

// 点击批次库存项
const onPiciClick = (pici) => {
  console.log('点击批次库存:', pici.id);

  // 将批次数据和API参数存入缓存
  const cacheData = {
    sourceData: pici, // 原始批次数据
    apiParams: {
      cat_id: '',
      cat_id_2: '',
      pici_id: pici.id,
      index: 1,
      page: 1,
      limit: 10,
      saleStatus: 1,
      goods_name: '',
    },
    pageType: 'pici',
  };

  uni.setStorageSync('stockPageData', JSON.stringify(cacheData));

  // 直接跳转，不传URL参数
  uni.navigateTo({
    url: '/pages/tab/batchadd/batchadd',
    success: () => {
      console.log('跳转成功，数据已缓存');
    },
    fail: (err) => {
      console.error('跳转失败:', err);
    },
  });
};
</script>
